package com.zsk.shop.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.base.page.BasePageFactory;
import com.zsk.shop.common.constant.RedisKeys;
import com.zsk.shop.common.utils.EntityConvertUtils;
import com.zsk.shop.common.utils.HttpContext;
import com.zsk.shop.common.utils.RedisUtil;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.DataDictionary;
import com.zsk.shop.entity.GopUser;
import com.zsk.shop.mapper.DataDictionaryMapper;
import com.zsk.shop.model.params.EditDataDictionaryParams;
import com.zsk.shop.model.results.DataDictionaryListResult;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ljh
 */
@Service
public class DataDictionaryService extends ServiceImpl<DataDictionaryMapper, DataDictionary> {

    @Resource
    private GopUserService gopUserService;

    private Integer queryByKey(String key) {
        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataDictionary::getKey, key);
        return this.list(queryWrapper).size();
    }

    public BaseResponse edit(EditDataDictionaryParams params) {
        if (ToolUtil.isOneEmpty(params, params.getId())) {
            return BaseResponse.error("当前id有误");
        }
        DataDictionary oldEntity = getOldEntity(params);
        if (ToolUtil.isEmpty(oldEntity)) {
            return BaseResponse.error("未找到当前系统参数,修改失败");
        }
        DataDictionary newEntity = getEntity(params);
        ToolUtil.copyProperties(newEntity, oldEntity);
        newEntity.setUpdateTime(new Date());
        newEntity.setUpdateUser(HttpContext.getUserId());
        if (this.updateById(newEntity)) {
            DataDictionary obj = this.getById(params.getId());
            if (ToolUtil.isNotEmpty(obj)) {
                RedisUtil.delete(obj.getKey());
                RedisUtil.set(RedisKeys.dictionaryKey(obj.getKey()), obj.getValue());
            }
        }
        return BaseResponse.success("修改成功");
    }

    private DataDictionary getOldEntity(EditDataDictionaryParams param) {
        return this.getById(param.getId());
    }

    private DataDictionary getEntity(EditDataDictionaryParams param) {
        param = EntityConvertUtils.setNullValue(param);
        DataDictionary entity = EntityConvertUtils.convertAToB(param, DataDictionary.class);
        return entity;
    }

    public BaseResponse<DataDictionaryListResult> dataDictionaryList(String name, String value) {
        Page pageContext = BasePageFactory.defaultPage();
        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
        if (ToolUtil.isNotEmpty(name)) {
            queryWrapper.like(DataDictionary::getName, name);
        }
        if (ToolUtil.isNotEmpty(value)) {
            queryWrapper.like(DataDictionary::getValue, value);
        }
        queryWrapper.eq(DataDictionary::getIsShow, true);
        queryWrapper.eq(DataDictionary::getIsDeleted, false);
        IPage page = this.page(pageContext, queryWrapper);
        List<DataDictionaryListResult> results = EntityConvertUtils.convertAListToBList(page.getRecords(), DataDictionaryListResult.class);
        List<Long> updateUserIds = results.stream().map(DataDictionaryListResult::getUpdateUser).collect(Collectors.toList());
        List<GopUser> gopUserList = gopUserService.queryNameByIds(updateUserIds);
        for (DataDictionaryListResult result : results) {
            Long updateUserId = result.getUpdateUser();
            GopUser gopUser = gopUserList.stream().filter(x -> x.getId().equals(updateUserId)).findFirst().orElse(new GopUser());
            result.setUpdateUserStr(gopUser.getName());
        }
        page.setRecords(results);
        return BasePageFactory.createPageInfo(page);
    }

    public DataDictionary getValueByKey(String key) {
        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataDictionary::getKey, key);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    /**
     * 获取数据字典中的所有数据
     *
     * @return
     * @author Ys
     * @date 2021/3/20 13:59
     */
    public List<DataDictionary> getDataDictionaryInfo() {
        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataDictionary::getIsShow, true);
        queryWrapper.eq(DataDictionary::getIsDeleted, false);
        List<DataDictionary> listT = this.list(queryWrapper);
        return listT;
    }

    private DataDictionary getDictionaryByKey(String key) {
        LambdaQueryWrapper<DataDictionary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataDictionary::getKey, key);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    public String getValueStrByKey(String key) {
        DataDictionary dataDictionary = getDictionaryByKey(key);
        if (ToolUtil.isNotEmpty(dataDictionary)) {
            return dataDictionary.getValue();
        }
        return null;
    }

    public void updateValueByKey(String value, String key) {
        if (ToolUtil.isEmpty(key)) {
            return;
        }
        LambdaUpdateWrapper<DataDictionary> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(DataDictionary::getValue, value);
        updateWrapper.set(DataDictionary::getUpdateTime, new Date());
        updateWrapper.eq(DataDictionary::getKey, key);
        this.update(updateWrapper);
    }
}
